<?php
class M_qin_region extends Cemvc_Db_MysqlDb{
  public $PrimaryKey='code';
  /*CEPHP会在要需要时查询主键，但主动设置主键可以使程序执行更快*/

  public function __construct()
  {
    parent::__construct();
    $this->SetDbCodeNames("utf8");
  }

  public function getProvinceList()
  {
    return $this->getRegion("code like '%0000'");
  }

  public function getCitiesList($province_id)
  {
    $head = substr($province_id, 0, 2);
    $city_code = $head . "%00"; 
    return $this->getRegion("code like '$city_code' and code != '$province_id'");
  }
  public function getTownsList($city_id)
  {
    $head = substr($city_id, 0, 4);
    $city_code = $head . "%"; 
    return $this->getRegion("code like '$city_code' and code != '$city_id'");
  }
    
  public function getRegion($where)
  {
    $res = $this->where(array($where))->fetchAll();
    $array = array();
    foreach($res as $region)
      {
	$array[$region['code']] = $region['name'];
      }
    return $array;
  }

  public function get_region_name($code)
  {
    $res = $this->where(array("code = $code"))->fetchOne();
    if ($res)
      return $res["name"];
    else
      return null;
  }

  /* return the province name > city name > town name */
  public function get_full_name($code)
  {
    $province_id = (int)((int)$code / 10000) * 10000;
    $city_id = (int)((int)$code / 100) * 100;
    
    $res = $this->where(array("code in ($province_id, $city_id, $code)"))->fetchAll();
    $str = '';
    foreach($res as $r)
      {
	$str .= $r["name"]." ";
      }
    if ($str)
      return $str;
    else
      return null;
  }

  public function get_selected_options($region_code)
  {
    $prov_id = substr($region_code, 0, 2)."0000";
    $city_id = substr($region_code, 0, 4)."00";

    $region = new M_qin_region();
    $provinces = $this->getProvinceList();
    $cities = $this->getCitiesList($prov_id);
    $towns = $this->getTownsList($city_id);

    return array("provinces" => M_Tools::make_options($provinces, $prov_id),
		 "cities" => M_Tools::make_options($cities, $city_id),
		 "towns" => M_Tools::make_options($towns, $region_code));
  }
}
?>
